package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.Entity.User;
import com.sky.constant.WechatConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties wechatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", wechatProperties.getAppid());
        params.put("secret", wechatProperties.getSecret());
        params.put("js_code", userLoginDTO.getCode());
        params.put("grant_type", "authorization_code");
        String s = HttpClientUtil.doGet(WechatConstant.LOGIN_URL, params);

        log.info("微信返回数据：" + s);

        JSONObject jsonObject = JSONObject.parseObject(s);
        String openid = jsonObject.getString("openid");
        if (openid == null) {
            return null;
        }
        User user = userMapper.queryUserByOpenId(openid);
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        return user;
    }
}
